package com.xyhuo.leetcode.january;

import com.xyhuo.leetcode.common.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * 二叉树展开为链表
 * https://leetcode.cn/problems/flatten-binary-tree-to-linked-list/
 *
 * @time 2024/1/10
 */
public class Flatten {

    public void flatten(TreeNode root) {
        search(root);
        for (int i = 0; i < list.size(); i++) {
            TreeNode node = list.get(i);
            node.left = null;
            if (i == list.size() - 1) {
                node.right = null;
            } else {
                node.right = list.get(i + 1);
            }
        }
    }

    private List<TreeNode> list = new ArrayList<>();

    private void search(TreeNode root) {
        if (null == root) {
            return;
        }
        list.add(root);
        search(root.left);
        search(root.right);
    }
}
